'use strict';

const uidObj = require('uni-id');
const {
	Controller
} = require('uni-cloud-router');

const dbcmd = uniCloud.database().command;

module.exports = class GroupBuyController extends Controller {
	
	// 待开团列表
	async waitList(){ 
		const {
			rows, 	// 每页数据条数
			ids,	// 过滤已存在数据ID
			val		// 最后一条数据值
		} = this.ctx.data;
	}
	
	// 待参团列表
	async joinList(){  
		let response = {
			code: 1,
			datas: {},
			msg: ''
		};
		
		const start = Date.now();
		const nowdate = start;
		
		const {
			group_id
		} = this.ctx.data;
		
		// 拼团活动
		await this.service.marketing.getGroup(group_id, false);
		
		// 参团中
		const groupChiefRes = await this.db.collection('usemall-market-groupbuy-member')
			.where({
				is_delete: 0,
				state: '参团中',
				group_id: group_id
			})
			.field({
				member_openid: false,
				group_member_pay_cnt: false,
				last_modify_time: false,
				last_modify_uid: false,
				last_modify_uname: false,
				create_uname: false,
				create_uid: false,
				create_time: false
			})
			.orderBy('group_member_pay_cnt', 'asc')
			.limit(8)
			.get();
			
		const end = Date.now();
		response.datas = [];
		// 剩余时间
		groupChiefRes.data.filter(x => x.group_num > x.group_members.length).forEach(x => {
			x.timestamp = (x.expire_time - end) / 1000;
			if (x.timestamp) response.datas.push(x);
		});
		
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 带参团数据
	async joinData() {
		let response = {
			code: 1,
			datas: {},
			msg: ''
		};
		
		const start = Date.now();
		const nowdate = start;
		
		let uid = '';
		if (this.ctx.event.uniIdToken) {
			// 已登录，获取当前登录 uid
			const userRes = await uidObj.checkToken(this.ctx.event.uniIdToken);
			if (userRes.code == 0) {
				uid = userRes.uid;
			}
		}
		if (!uid) {
			response.msg = '当前未登录'
			return response;
		}
		
		const {
			id
		} = this.ctx.data;
		
		if (!id || id.split('_').length !== 2) {
			response.msg = '拼单参数错误，参团失败';
			return response;
		}
		
		// 团长ID
		const group_chief_id = id;
		// 订单ID
		const order_id = id.split('_')[1];
		
		// 开团数据
		response.group_chief = await this.service.marketing.getGroupChief(group_chief_id, false);
		// 拼团活动
		response.group = await this.service.marketing.getGroup(response.group_chief.group_id, false);
		
		// 订单时间
		let order_time = 0;
		// 配置时间
		let order_config_time = 0;
		
		const order = this.db.collection('usemall-order').where({
			is_delete: 0,
			order_id: order_id
		}).get();
		const order_detail = this.db.collection('usemall-order-detail').where({
			order_id: order_id
		}).get();
		const orderConfigRes = this.db.collection('usemall-order-parameter').limit(1).get();
		
		const datas = await Promise.all([order, order_detail, orderConfigRes]);
		
		[response.order] = datas[0] && datas[0].data;
		response.order_detail = datas[1] && datas[1].data;
		
		// 订单配置
		const [orderConfig] = datas[2] && datas[2].data;
		response.order_config = orderConfig;
		
		switch (response.order.state) {
			case '待成团':
				response.expire_time = parseInt((response.order.order_expire_time - Date.now()) / 1000);
				break;
		}
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
	// 拼团数据
	async datas() {
		let response = {
			code: 1,
		};
		
		const {
			rows, 	// 每页数据条数
			ids,	// 过滤已存在数据ID
			val		// 最后一条数据值
		} = this.ctx.data;
		
		const start = Date.now();
		const nowdate = Date.now();
		
		// 获取拼团数据
		const groupRes = await this.db.collection('usemall-market-groupbuy').where({
				is_delete: 0,
				state: '启用',
				group_begin_time: this.db.command.lt(nowdate),
				group_end_time: this.db.command.gt(nowdate)
			})
			.orderBy('sort', 'asc')
			.limit(rows || 8)
			.field({
				goods_id: true,
				goods_obj: true,
				goods_price: true,
				group_num: true,
				group_begin_time: true,
				group_end_time: true,
				group_time: true,
				group_members: true,
				group_member_cnt: true
			})
			.get();
		
		response.datas = groupRes.data;
		if (response.datas && response.datas.length) {
			const curdate = Date.now();
			response.datas.forEach(x => {
				x.expires_time = (x.group_end_time - curdate) / 1000;
			});
		}
		
		const end = Date.now();
		console.log(`耗时：${end - start}ms`);
		response.code = 0;
		response.msg = `耗时：${end - start}ms`;
		return response;
	}
	
}
